//供应商页面
var EDITMODE=false;//false表示增加，true表示编辑供应商
var sType = getUrlParam("type"); //sType  1暂定裸钻，2 统包 3成品，4彩宝，5翡翠，6素金
(function(){
	var supplier={
		init:function(){
			this.bindEvents();
			this.getSupplier();//获取客户列表
			this.getSupplierRoles();//获取供应商角色
		},
		bindEvents:function(){
			var self=this;
			$("#add_shipTime").multipleSelect({
                placeholder: _("请选择"),
                selectAllText: _("全选")
                // filter: true
            });
			//状态切换搜索1
		    var url = window.location.href;
		    $('#categories li a').each(function () {
		        if (returnUrl($(this).attr('href'))== returnUrl(url)){
		            $(this).parents("li").addClass('cur');
		        }
		    });
			//按钮状态切换搜索
	        $("#_sysStatus ul li").click(function(){
	            $(this).addClass("add_blue").siblings().removeClass("add_blue");
	           	self.getSupplier();
	        });
	        //搜索筛选-出页面
	        $("#show_term_btn").on("click", function () {
				myApp.popup(".customer_filter_box");
			});
			//搜索
            $("#confirm_btn").on("click",function () {
               $(".customer_filter_box").hide();//关闭弹框
               self.getSupplier();
            });
	        //点击行展开详情
			$("#product_table").on("click", "tr.data_tr td", function (event) {
			    var td_input = $(this).index();
			    if (td_input == 0) {
			        //勾选框不展开详情
			    } else {
			        $(this).parent("tr").next(".stock_detail").slideToggle(0);
			    }
			    
			});
			//点击全选
			$("#checkbox_check_all").on("click",function(){
				$(this).toggleClass("selected");
				if($(this).hasClass("selected")){
					$("#stock_body .check_list_box").children("span").addClass("selected");
					$("#stock_body .check_list_box").closest("tr").addClass('tr_select_color');//全选tr加背景色
					$("#transfer,#role_btn").css("background-color", primary_color);//按钮样式
			        $("#transfer,#role_btn").attr("disabled", false);
				}else{
					$(".check_list_box").children("span").removeClass("selected");
					$("#stock_body .check_list_box").closest("tr").removeClass('tr_select_color');
					self.clearBtn();
				}
			});
			//列表的勾选框--按序号选中
			$("#stock_body").on("click",".check_rel",function(){
				$(this).find('.check_list_box').children("span").toggleClass("selected");
                if($(this).find('.check_list_box').children("span").hasClass("selected")){
					 $(this).closest("tr").addClass('tr_select_color');
				}else{
					 $(this).closest("tr").removeClass('tr_select_color');
				}
				//判断是否全选，全选选中
				var length=$("#stock_body .check_list_box span").length;
				var checkLength=$("#stock_body .check_list_box span.selected").length;
				if(checkLength>0){//给按钮批量删除添加颜色
					$("#transfer,#role_btn").css("background-color", primary_color);
			        $("#transfer,#role_btn").attr("disabled", false);
				}else{//去掉按钮批量删除的颜色
					self.clearBtn();
				}
				if(length==checkLength){//全选按钮选中
					$("#checkbox_check_all").addClass("selected");	
				}else{
					$("#checkbox_check_all").removeClass("selected");
				}
			});
			proShow("mod_productType");//表格显示对应的产品折扣与倍率
            //删除
            $("#stock_body").on("click",".del_btn",function(){
            	var dataId=$(this).attr("data-id");//需要删除的id
            	myApp.confirm(_("此操作无法撤回，确认删除选中的供应商？"),function(){
            		self.delSupplier(dataId);
            	});
            });
            //批量删除
            $("#transfer").on("click",function(){
            	var checkeds = $("#product_table tbody .check_list_box span.selected"); //选中
            	checkeds.length<=0?myApp.alert(_("未选中任何供应商")):myApp.confirm(_("此操作无法撤回，确认删除选中的供应商？"),function(){
            		self.delSupplier("multi-line");
            	});
            });
            //批量修改供应商角色
            $("#role_btn").on("click",function(){
            	var self=this;
            	myApp.popup("#batch_RoleName_box");
            });
            //批量修改供应商角色输入验证--
            var validate = $("#batch_RoleName_form").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    self.batchSupplierRole();//客户充值-修改供应商角色
                },
                rules: {
                    RoleNames:"required",                   
                },
                messages: {
                    RoleNames: "",
                }
            });
            //编辑供应商-
            $("#stock_body").on("click",".handle_div a.edit_power_btn",function(){
            	var id=$(this).attr("data-id");
				$("#customer_form_title").text(_("编辑供应商"));
            	EDITMODE=true;
            	self.bindData(id,"form_data");//获取到供应商的详情
				myApp.popup(".supplier_form_box");//弹框出现
            });//----
            //新增编辑供应商输入验证 ---
            var validate = $("#form_data").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    self.editSupplier();//编辑供应商
                },
                rules: {
                    SupplierCode: { //name
                        required: true,
                    },
                    SupplierName:"required", 
                    DeliveryAddress: "required", 
                    Rebate: "required", 
                    FancyRebate: "required", 
                    Sort: "required", 
                },
                messages: {
                    SupplierCode: "",//简称
                    SupplierName:"",//全称
                    DeliveryAddress: "",//取货地址
                    Rebate: "",//白钻加点
                    FancyRebate: "",//彩钻加点
                    Sort: "",//取货次序
                }
            });
           
		},
		//清除按钮颜色
		clearBtn:function(){
			$(".search_btn_b").css("background-color","#a1a1a1");
			$(".search_btn_b").attr("disabled",true);
		},
		//删除
        delSupplier:function(me) {
        	var self=this;
            var codes = [];
			if (me == "multi-line") {
                checkeds = $("#product_table tbody .check_list_box span.selected"); //选中
                console.log(checkeds.length)
                for (var i = 0; i < checkeds.length; i++) {
                    codes.push($(checkeds[i]).attr("lang"));
                }
            }else {
                codes.push(me);
            }
            if (codes.length > 0) {
				var r = {};
                r.SupplierIds = codes;//要删除的id的集合
                $.ajax({
                    url: "/Team/DelSupplier",//提交地址
                    type: "POST",//提交方式
                    data: JSON.stringify(r),
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {//返回的是删除的条数
                    	if (result >0) {
	                        myApp.alert(_("删除成功"),function(){
	                        	$("#checkbox_check_all").removeClass("selected");//去掉全选按钮的样式
	                        	self.getSupplier();//删除成功后再请求一次数据
	                        	
	                        });
	                    } else {
	                        myApp.alert(_("删除失败"));//删除失败
	                    }
                    }
                });
            }
        },
		
		//获取供应商详情,绑定数据                   
		bindData:function(ID,form_data){
		    myApp.showIndicator();//显示加载中
			//var self=this;
			var submitJson={};
			submitJson.SupplierID=ID;//编辑的id
			$.ajax({
				url:'/Team/GetSupplierInfo',//获取供应商详情
				type:'POST',
				data: JSON.stringify(submitJson),
				dataType:'JSON',
				contentType: "application/json; charset=utf8",
				success:function(result){//获取到的对应的详情
					myApp.hideIndicator();//隐藏加载中	
					$("#add_shipTime").multipleSelect("setSelects", []); //清空--
					var data=eval('(' + result + ')');
					$("#"+form_data).setForm(data);//绑数据--
					$("#id_input").prop({"name":"SupplierID","value":data.SupplierID});//ID	
					if (data.ShipTime && data.ShipTime != "") {
                        $("#add_shipTime").multipleSelect("setSelects", data.ShipTime.split(',')); //设置选中--
                  }
				}
			});
		},
		//编辑供应商
		editSupplier:function(){
			var self=this;
			myApp.showPreloader(_('正在提交中，请稍等...'));
			 var requestSupplier = $('#form_data').serializeArray().reduce(function(result, item){
	            result[item.name] = item.value;
	            return result;
	        }, {})//把提交的数据转为JSON格式
//	        requestSupplier.IsRebate=$("#rebate_switch").attr("data-type");//白钻加点的内容
	        var roleVal=[];
	        var addTime=[];
	        roleVal.push($("#form_RoleName").val());
	        addTime.push($("#add_shipTime").val());
			requestSupplier.SupplierType=sType;
		    if(roleVal!=null){//提交供应商角色
		    	requestSupplier.RoleNames=roleVal.join(",");
		    }
		    if(addTime!=null){//提交发货时间
		    	requestSupplier.shipTime=addTime.join(",");
		    }
	        if(EDITMODE){
	        	var submitUrl="/Team/EditSupplier";
	        }else{
	        	var submitUrl="";
	        }
	        $.ajax({
		        url: submitUrl,//提交地址
		        type: "POST",//提交方式
		        data: JSON.stringify(requestSupplier),
		        contentType: "application/json; charset=utf-8",
		        success: function (result) {//修改成功后返回的数据
		            var _result = eval('(' + result + ')');//eval()解析单个json对象	
		            myApp.hidePreloader();//隐藏加载中
		            if(_result.msgcode == true){		
		                myApp.alert(_(_result.msginfo),function(){
		                	self.getSupplier();	//编辑完成后重新请求一次数据，？
		                });
		            }else{
		                myApp.alert(_(_result.msginfo));
		            }
		        }
		    });
		},
		//获取供应商角色
		getSupplierRoles:function(){
			$.ajax({
				type:"POST",
				url:"/team/QuerySupplierRole",
				success:function(result){
					var res=eval('('+result+')');
					if(res.msgcode==true){
						var $html=[];
						for(var i=0;i<res.msginfo.length;i++){
							var data=res.msginfo[i];
							if(sType==1 && data.GoodsType==1){
                                $html.push(
                                    '<option value='+data.ID+'>'+data.RoleName+'</option>'
                                );
							}else if(sType==2 && data.GoodsType ==2){
                                $html.push(
                                    '<option value='+data.ID+'>'+data.RoleName+'</option>'
                                );
							}else if(sType==3 && data.GoodsType ==3){
                                $html.push(
                                    '<option value='+data.ID+'>'+data.RoleName+'</option>'
                                );
							}
						}
                        $html.push(
                            '<option value="0">无</option>'
                        );
						$("#form_RoleName,#batch_RoleName").html($html);
					}else{
						$("#form_RoleName,#batch_RoleName").html("");
					}
				}
			});
		},
		
		//批量修改供应商角色
		batchSupplierRole:function(){
			var self=this;
            //OrderIDs值组装 _orderIDs="232,324"
            var supplierlistCb = $("#stock_body .check_rel span.selected");//checked的
            var _supplierIDs = [];//批量修改的id的集合
            for (var i = 0; i < supplierlistCb.length; i++) {
                _supplierIDs.push(supplierlistCb[i].lang);
            }
            var submitJson={};
            var roleVal=[];//-----!!!
            roleVal.push($("#batch_RoleName").val());//供应商角色id
            submitJson.SupplierRoleID=roleVal.join(",");//
		    submitJson.SupplierIDs=_supplierIDs;
		    console.log(submitJson)
			$.ajax({
				url:"/team/BatchUpdateSupplierRoleIDBySupplierIDs",
				type:"POST",
				data:JSON.stringify(submitJson),
				contentType: "application/json; charset=utf-8",
                success: function (result) {//返回修改成功的信息
                	var res=eval('('+result+')');  
                	console.log(res)
                	if(res.msgcode==true){
                		toast(res.msginfo);//--显示批量修改供应商角色成功提示框
                		$("#batch_RoleName_box").hide();
                  		self.getSupplier();	
                		$("#checkbox_check_all").removeClass("selected");//修改成功后去掉全选按钮的颜色
                		self.clearBtn();//去掉 按钮修改角色 的颜色
                	}else{
                		toast(res.msginfo);
                		myApp.alert(_(res.msginfo));
                	}
                }
			});
		},
		//加载供应商列表内容
		getSupplier:function() {
			var self=this;
			myApp.showIndicator();//显示加载中
		    var requestSupplier = getParamer();
		    requestSupplier.PageIndex="1";
            requestSupplier.PageSize="500";
			requestSupplier.SupplierType=sType;
			console.log(requestSupplier)
		    $.ajax({
		        url: "/team/GetSuppliers",//提交地址
		        type: "POST",//提交方式
		        data: JSON.stringify(requestSupplier),
		        contentType: "application/json; charset=utf-8",
		        success: function (result) {
		        	myApp.hideIndicator();//隐藏加载中
		            self.BindingData(result, $("#product_table tbody"));//绑定
		        }
		    });
		},

//		//数据绑定
        BindingData:function(Datas, tableTbody) {
            var tableTbody = $("#stock_body");
            var _result = eval('(' + Datas + ')');//eval()解析单个json对象
            if(_result.msgcode == false){
                var tr = "";//单行
                var tds = "<td colspan='6' style='text-align:center;color:red'>" + _(_result.msginfo) + "</td>";// 多列合成一列并居中
                tr = "<tr>" + tds + "</tr>";//将多列加到一行
                tableTbody.html(tr);//加入到id为product_table的table的tbody中
                myApp.hideIndicator();//隐藏加载中

            }else{
//              var _balance = 0;//总余额 12-1
//              var _usdbalance = 0;//总余额 12-1
                _result = _result.Data;//object
                console.log(_result);//
                var trs = "";//多行数据
                for (var i = 0; i < _result.length; i++) {
                    var tds = "";//多列
                    var tr = "";//单行
                    var tr_div = "";
//                  tds += "<td>" + (i + 1) + "</td>";
                    tds += "<td class='check_rel'>"+
                    "<div class='check_list_box'><span class='checkbox' name='checkbox' lang='" + _result[i].SupplierID + "'></span></div>";//1供应商ID
					tds += "<td>" + partShowSubstring(_result[i].SupplierCode) + "</td>";//2账号
					tds += "<td>" + partShowSubstring(_result[i].SupplierShortName) + "</td>";//3简称
					tds += "<td>" + partShowSubstring(_result[i].SupplierName) + "</td>";//4全称
					tds += "<td>" + partShowSubstring(_result[i].Country) + "</td>";//5国家
                    tds += "<td class='cus_sysStatus' lang='"+ _result[i].SysStatus +"' data-balance='"+ _result[i].Balance +"'  data-USDBalance='"+ _result[i].USDBalance +"'>" + sysStatusFormat(_result[i].SysStatus) + "</td>";//6状态
                    tr += "<tr class='data_tr'>" + tds + "</tr>";//将多列加到一行
                    tr_div="<tr class='stock_detail'><td  colspan='6'>"+
                    "<div class='detail_left' style='width:50%;'>"+   
                    	"<i><b>"+_("帐号")+"：</b>"+_result[i].SupplierCode+"</i>"+
                    	"<i><b>"+_("简称")+"：</b>"+NullFormat(_result[i].SupplierShortName)+"</i>"+
                    	"<i><b>"+_("全称")+"：</b>"+NullFormat(_result[i].SupplierName)+"</i>"+
                    	"<i><b>"+_("国家")+"：</b>" +NullFormat(_result[i].Country)+ "</i>" +
                        "<i><b>"+_("取址")+"：</b>" +NullFormat(_result[i].DeliveryAddress)+ "</i>"+
                        "<i><b>"+_("网站")+"：</b>" +NullFormat(_result[i].Url)+ "</i>";
					if(isHideSupplier == "1"){
						tr_div+="<i style='display:"+(sType=='1'?'block':'none')+"'><b>"+_("白钻加点")+"：</b>"+NullFormat(_result[i].Rebate)+"</i>"+
							"<i style='display:"+(sType=='1'?'block':'none')+"'><b>"+_("彩钻加点")+"：</b>"+NullFormat(_result[i].FancyRebate)+"</i>"+
							"<i style='display:"+(sType=='2'?'block':'none')+"'><b>"+_("统包折扣")+"：</b>"+NullFormat(_result[i].ParcelRebate)+"</i>"+
							"<i style='display:"+(sType=='3'?'block':'none')+"'><b>"+_("成品折扣")+"：</b>"+NullFormat(_result[i].RingRebate)+"</i>"+
							"<i style='display:"+(sType=='4'?'block':'none')+"'><b>"+_("彩宝折扣")+"：</b>"+NullFormat(_result[i].GemRebate)+"</i>"+
							"<i style='display:"+(sType=='5'?'block':'none')+"'><b>"+_("翡翠折扣")+"：</b>"+NullFormat(_result[i].EmeraldRebate)+"</i>"+
							"<i style='display:"+(sType=='6'?'block':'none')+"'><b>"+_("素金折扣")+"：</b>"+NullFormat(_result[i].PrimeGoldRebate)+"</i>";

					}

					tr_div+="</div>" +
                    "<div class='detail_middle' style='width:50%;'>"+
                    	"<i><b>"+_("RapID")+"：</b>"+NullFormat(_result[i].RapnetID)+"</i>"+
                    	"<i><b>"+_("Skype")+"：</b>"+NullFormat(_result[i].Skype)+"</i>"+
                    	"<i><b>"+_("Email")+"：</b>"+NullFormat(_result[i].Email)+"</i>"+
                    	"<i><b>"+_("顺序")+"：</b>"+_result[i].Sort+"</i>"+
                    	"<i><b>"+_("更新")+"：</b>"+DateTimeFormat(_result[i].UpdateTime)+"</i>"+
                    	"<i><b>"+_("创建")+"：</b>"+DateTimeFormat(_result[i].CreateTime)+"</i>"+
                    	"<i><b>"+_("状态")+"：</b>"+sysStatusFormat(_result[i].SysStatus)+"</i>"+
                    "</div>"+
                    "<div class='handle_div'>"+
                        "<a href='#' class='edit_power_btn' data-id='" + _result[i].SupplierID + "'>"+_("修改")+"</a>"+
                        "<a href='#' class='modify_btn del_btn' data-id='" + _result[i].SupplierID + "'>"+_("删除")+"</a>"+
                    "</div></td></tr>";
//                  tr_div+="<div style='height:30px;clear:both'>"+ _result[i].CustomerID+"</div></td></tr>";
                    trs += tr+tr_div;//将单行加到多行
                }
                tableTbody.html(trs);//加入到id为product_table的table的tbody中
//              currentShow();  //币种设置
                myApp.hideIndicator();//隐藏加载中
                //下拉框优化 10-28
		        var options = "";
		        options += '<option value="">'+_("简称")+'</option>';
		        for (var i = 0; i < _result.length; i++) {
		            options += '<option value="' + $.trim(_result[i].SupplierCode) + '"  >' + $.trim(_result[i].SupplierCode) + '</option>';//解决因为空格导致简称无法搜索 10-27
		        }
		        $("#_customerNickName").html("");//供应商简称搜索下拉
		        $("#_customerNickName").html(options);
		            }  
		        },
	}
	supplier.init();
})();
//表格显示对应的产品折扣与倍率
function proShow(className) {
	var classType = $("." + className);
	var _disPlay = "";
	if(className=="mod_productType"){
		_disPlay = "block";
	}else{
		_disPlay = "inline-block";
	}
	$(classType[sType]).css("display", _disPlay).siblings("." + className).css("display", "none");
	//白、彩钻
	if(sType == 1) {
		var classType = $("." + className);
		$(classType[0]).css("display", _disPlay).siblings("." + className).css("display", "none");
		$(classType[1]).css("display", _disPlay);
	}
}
//供应商状态格式化
function sysStatusFormat(sysStatusValue) {
    if (sysStatusValue == -1) {
        return _("已删");
    } else if (sysStatusValue == 1) {
        return _("正常");
    } else {
        return sysStatusValue;
    }
}
////数据状态格式化
//function datastateFormat(datastateValue) {
//  if (datastateValue == 1) {
//      return _("开");
//  } else if (datastateValue == 0) {
//      return "<b style='color:red;font-weight:bold;'>"+_("关")+"</b>";
//  } else {
//      return datastateValue;
//  }
//}
//获取参数
function getParamer() {
    var requestSupplier = {};
    requestSupplier.is_stock = $("#_spotdata").val();//现货供应商开关 1-10
    requestSupplier.SysStatus = $("#_sysStatus1").val();//状态
    requestSupplier.SupplierCode = $.trim($("#_supplierCode").val());//简称
    requestSupplier.SupplierName = $.trim($("#_supplierName").val()); //全称           
    requestSupplier.DeliveryAddress = $.trim($("#_deliveryAddress").val());//取货地址
    requestSupplier.Country = $.trim($("#_country").val());//国家-
    requestSupplier.PageSize = $("#_pageSizes").val(); //id=_pageSizes
    requestSupplier.PageIndex = $("#page_num").html();//.page_num是class
    return requestSupplier;
};


//以下为截取url的方法，a链接跳转加样式
function returnUrl(href){
    var number=href.lastIndexOf("/");
    return href.substring(number+1);
};
function returnFileName(href){
    var number1=href.lastIndexOf("/");
    var number2= href.substring(0,number1).lastIndexOf("/");
    return href.substring(number1,number2+1);
};


//角色权限管理跳转路径
function supplierClickUrl(me){
    $(me).attr('href','/team/SupplierRole?type='+sType+'')
}